import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from app.models.user import User
from app.models.data import PlantingData, CropVariety, EnvironmentData
from datetime import datetime, timedelta
import random

def create_test_users():
    """创建测试用户"""
    users = [
        {'username': 'admin', 'password': 'admin123', 'user_type': 'admin'},
        {'username': 'farmer1', 'password': '123456', 'user_type': 'farmer'},
        {'username': 'researcher1', 'password': '123456', 'user_type': 'researcher'},
        {'username': 'gov1', 'password': '123456', 'user_type': 'government'},
        {'username': 'enterprise1', 'password': '123456', 'user_type': 'enterprise'}
    ]
    
    created_users = []
    for user_data in users:
        user = User(username=user_data['username'], user_type=user_data['user_type'])
        user.set_password(user_data['password'])
        db.session.add(user)
        created_users.append(user)
    
    db.session.commit()
    print("测试用户创建完成")
    return created_users

def create_crop_varieties():
    """创建作物品种数据"""
    varieties = [
        {
            'name': '郑单958',
            'crop_type': '玉米',
            'characteristics': '抗病性强，适应性广',
            'yield_potential': '700-800公斤/亩',
            'market_value': '2.2元/公斤'
        },
        {
            'name': '济麦22',
            'crop_type': '小麦',
            'characteristics': '抗寒性好，抗倒伏',
            'yield_potential': '500-600公斤/亩',
            'market_value': '2.5元/公斤'
        },
        {
            'name': '中稻3号',
            'crop_type': '水稻',
            'characteristics': '米质优良，产量稳定',
            'yield_potential': '600-700公斤/亩',
            'market_value': '3.0元/公斤'
        }
    ]
    
    for variety in varieties:
        crop = CropVariety(**variety)
        db.session.add(crop)
    
    db.session.commit()
    print("作物品种数据创建完成")

def create_planting_data(users):
    """创建种植数据"""
    # 获取农户和企业用户
    farmer_users = [user for user in users if user.user_type in ['farmer', 'enterprise']]
    
    regions = ['华北平原', '东北平原', '长江中下游平原', '四川盆地']
    crop_types = ['玉米', '小麦', '水稻', '大豆']
    
    try:
        # 生成正常数据
        for user in farmer_users:
            for _ in range(10):  # 每个用户10条数据
                data = PlantingData(
                    user_id=user.id,
                    crop_type=random.choice(crop_types),
                    area=round(random.uniform(10, 1000), 2),  # 保留两位小数
                    region=random.choice(regions),
                    plot_number=f'P{random.randint(1000, 9999)}',
                    planting_date=datetime.now() - timedelta(days=random.randint(1, 365))
                )
                db.session.add(data)
        
        # 生成一些异常数据
        if farmer_users:
            anomaly_data = [
                # 面积异常 - 太小
                PlantingData(
                    user_id=farmer_users[0].id,
                    crop_type='玉米',
                    area=0.1,
                    region='华北平原',
                    plot_number='P0001',
                    planting_date=datetime.now()
                ),
                # 面积异常 - 太大
                PlantingData(
                    user_id=farmer_users[0].id,
                    crop_type='小麦',
                    area=10000,
                    region='东北平原',
                    plot_number='P0002',
                    planting_date=datetime.now()
                ),
                # 日期异常 - 未来日期
                PlantingData(
                    user_id=farmer_users[0].id,
                    crop_type='水稻',
                    area=500,
                    region='长江中下游平原',
                    plot_number='P0003',
                    planting_date=datetime.now() + timedelta(days=30)
                ),
                # 空值异常
                PlantingData(
                    user_id=farmer_users[0].id,
                    crop_type='',
                    area=300,
                    region='四川盆地',
                    plot_number='P0004',
                    planting_date=datetime.now()
                )
            ]
            
            for data in anomaly_data:
                db.session.add(data)
        
        db.session.commit()
        print("种植数据创建完成")
        
    except Exception as e:
        print(f"创建种植数据时出错: {str(e)}")
        db.session.rollback()

def create_environment_data():
    """创建环境数据"""
    regions = ['华北平原', '东北平原', '长江中下游平原', '四川盆地']
    soil_types = ['砂质土', '壤土', '粘土', '砂壤土', '粘壤土']
    soil_fertility = ['高', '中', '低']
    
    # 生成正常数据
    for region in regions:
        for _ in range(20):
            data = EnvironmentData(
                region=region,
                date=datetime.now() - timedelta(days=random.randint(1, 365)),
                temperature=random.uniform(-10, 35),
                rainfall=random.uniform(0, 100),
                soil_type=random.choice(soil_types),
                soil_fertility=random.choice(soil_fertility),
                light_intensity=random.uniform(1000, 100000)
            )
            db.session.add(data)
    
    # 生成一些异常数据
    anomaly_data = [
        # 温度异常
        EnvironmentData(region='华北平原', date=datetime.now(), temperature=-60,
                       rainfall=50, soil_type='壤土', soil_fertility='中',
                       light_intensity=50000),
        # 降雨量异常
        EnvironmentData(region='东北平原', date=datetime.now(), temperature=25,
                       rainfall=-10, soil_type='砂质土', soil_fertility='高',
                       light_intensity=60000),
        # 光照强度异常
        EnvironmentData(region='长江中下游平原', date=datetime.now(), temperature=30,
                       rainfall=80, soil_type='粘土', soil_fertility='低',
                       light_intensity=-1000),
        # 日期异常
        EnvironmentData(region='四川盆地', date=datetime.now() + timedelta(days=30),
                       temperature=28, rainfall=60, soil_type='砂壤土',
                       soil_fertility='中', light_intensity=70000)
    ]
    
    for data in anomaly_data:
        db.session.add(data)
    
    db.session.commit()
    print("环境数据创建完成")

def main():
    app = create_app()
    with app.app_context():
        # 先清空现有数据
        try:
            db.session.query(PlantingData).delete()
            db.session.query(CropVariety).delete()
            db.session.query(EnvironmentData).delete()
            db.session.query(User).delete()
            db.session.commit()
            print("现有数据清除完成")
        except Exception as e:
            print(f"清除数据时出错: {str(e)}")
            db.session.rollback()
            return
        
        try:
            # 创建测试数据
            users = create_test_users()
            create_crop_varieties()
            create_planting_data(users)
            create_environment_data()
            print("所有测试数据创建完成！")
            
            # 打印测试账号信息
            print("\n测试账号信息：")
            print("管理员账号: admin / admin123")
            print("农户账号: farmer1 / 123456")
            print("科研人员账号: researcher1 / 123456")
            print("政府人员账号: gov1 / 123456")
            print("企业账号: enterprise1 / 123456")
            
        except Exception as e:
            print(f"创建测试数据时出错: {str(e)}")
            db.session.rollback()

if __name__ == '__main__':
    main() 